<?php

function qdrupal_bootstrap() {
  // Create the writable QDrupal directory
  $sQdrupalPath = file_create_path('qdrupal');
  file_check_directory($sQdrupalPath, FILE_CREATE_DIRECTORY);

  /**
   * Set up tons of paths
   */
  define('DS', DIRECTORY_SEPARATOR);
  define('PS', PATH_SEPARATOR);
  define('QDRUPAL_ROOT',dirname(__FILE__));

  define ('__DOCROOT__', getenv('DOCUMENT_ROOT'));
  define ('__VIRTUAL_DIRECTORY__', '');
  define ('__SUBDIRECTORY__', base_path().drupal_get_path('module','qdrupal').DS.'qcodo'.DS.'wwwroot');

  define('DRUPAL_ROOT',__DOCROOT__ . base_path());
  define('QDRUPAL_WRITABLE_PATH',DRUPAL_ROOT.$sQdrupalPath);
  define('QCODO_DIST',QDRUPAL_ROOT . DS . 'qcodo');
  define('QCODO_DEFAULT_CODEGEN',QCODO_DIST . DS . 'wwwroot' . DS . '_devtools' . DS . 'codegen_settings.xml');
  define('QCODO_DEFAULT_CONFIGURATION',QCODO_DIST . DS . 'wwwroot' .  DS . 'includes' . DS . 'configuration_pro.inc.php');

  define('QDRUPAL_FORMS',QDRUPAL_WRITABLE_PATH . '/forms');

  // TODO
  define('DB_CONNECTION_1', serialize(array(
	'adapter' => 'MySqli5',
	'server' => 'localhost',
	'port' => null,
	'database' => 'addressbook',
	'username' => 'root',
	'password' => '',
	'profiling' => variable_get('qdrupal_enable_profiling',false))));

  define ('ALLOW_REMOTE_ADMIN', user_access('administer qdrupal'));
  define ('__URL_REWRITE__', 'apache');

  define ('__DEVTOOLS_CLI__', __DOCROOT__ . __SUBDIRECTORY__ . '/../_devtools_cli');
  define ('__INCLUDES__', __DOCROOT__ .  __SUBDIRECTORY__ . '/includes');
  define ('__QCODO__', __INCLUDES__ . '/qcodo');
  define ('__QCODO_CORE__', __INCLUDES__ . '/qcodo/_core');

  define ('__DATA_CLASSES__', QDRUPAL_WRITABLE_PATH . '/data_classes');
  define ('__DATAGEN_CLASSES__', QDRUPAL_WRITABLE_PATH . '/data_classes/generated');
  define ('__DATA_META_CONTROLS__', QDRUPAL_WRITABLE_PATH . '/data_meta_controls');
  define ('__DATAGEN_META_CONTROLS__', QDRUPAL_WRITABLE_PATH . '/data_meta_controls/generated');

  define ('__DEVTOOLS__', __SUBDIRECTORY__ . '/_devtools');
  define ('__FORM_DRAFTS__', base_path() . $sQdrupalPath . '/drafts');
  define ('__PANEL_DRAFTS__', base_path() . $sQdrupalPath . '/drafts/dashboard');
  
  // We don't want "Examples", and we don't want to download them during qcodo_update
  define ('__EXAMPLES__', null);

  define ('__JS_ASSETS__', __SUBDIRECTORY__ . '/assets/js');
  define ('__CSS_ASSETS__', __SUBDIRECTORY__ . '/assets/css');
  define ('__IMAGE_ASSETS__', __SUBDIRECTORY__ . '/assets/images');
  define ('__PHP_ASSETS__', __SUBDIRECTORY__ . '/assets/php');

  if ((function_exists('date_default_timezone_set')) && (!ini_get('date.timezone')))
    date_default_timezone_set('America/Los_Angeles');

  define('ERROR_PAGE_PATH', __PHP_ASSETS__ . '/_core/error_page.php');
  define('ERROR_LOG_PATH', QDRUPAL_WRITABLE_PATH . '/error_log');

  //define('ERROR_FRIENDLY_PAGE_PATH', __PHP_ASSETS__ . '/friendly_error_page.php');
  //define('ERROR_FRIENDLY_AJAX_MESSAGE', 'Oops!  An error has occurred.\r\n\r\nThe error was logged, and we will take a look into this right away.');
}

function qdrupal_prepend() {
  if(defined('__PREPEND_INCLUDED__')) return;

  qdrupal_bootstrap();

  require(__QCODO_CORE__ . '/qcodo.inc.php');
  //echo "<xmp>"; echo $strContent; exit(date("H:i:s"));

  abstract class QApplication extends QApplicationBase {
	/**
	 * This is called by the PHP5 Autoloader.  This method overrides the one in ApplicationBase.
	 * @return void
	 */
	public static function Autoload($strClassName) {
	  // First use the Qcodo Autoloader
	  if (!parent::Autoload($strClassName)) {
	    // TODO: Run any custom autoloading functionality (if any) here...
	  }
	}
    public static $EncodingType = 'UTF-8';
  }

  if (array_key_exists('SERVER_PROTOCOL', $_SERVER)) {
    set_error_handler('qdrupal_error_handler');
    set_exception_handler('QcodoHandleException');
  }

  QApplication::Initialize();
  QApplication::InitializeDatabaseConnections();

  if (isset($_SESSION)) {
    if (array_key_exists('country_code', $_SESSION))
      QApplication::$CountryCode = $_SESSION['country_code'];
	if (array_key_exists('language_code', $_SESSION))
      QApplication::$LanguageCode = $_SESSION['language_code'];
  }

  // TODO - Add Drupal language integration
  if (QApplication::$LanguageCode)
    QI18n::Initialize();
  else {
	// QApplication::$CountryCode = 'us';
	// QApplication::$LanguageCode = 'en';
	// QI18n::Initialize();
  }

  define('__PREPEND_INCLUDED__', 1);
}

class QDrupalException extends Exception {
}

function qdrupal_error_handler($__exc_errno, $__exc_errstr, $__exc_errfile, $__exc_errline,$blnExit = TRUE) {
  ob_start();
  QcodoHandleError($__exc_errno, $__exc_errstr, $__exc_errfile, $__exc_errline,$blnExit = FALSE);
  $strContent = ob_get_clean();
  throw new QDrupalException($strContent);
}

function qdrupal_restore_drupal_error_handler() {
  set_error_handler('drupal_error_handler');
}
